package com.frogs.ucenter.v1.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.frogs.api.wechat.util.TemplateUtil;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.AttentionStateEnum;
import com.frogs.system.util.HdcAttentionListTypeEnum;
import com.frogs.system.util.HdcReceiveStateEnum;
import com.frogs.system.util.SexEnum;
import com.frogs.system.util.SwitchEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.RequestIllegalException;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.dao.FamilyBaseInfoDao;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.entity.FamilyBaseInfo;
import com.frogs.ucenter.entity.UserAttentionInfo;
import com.frogs.ucenter.entity.WechatUserBaseInfo;
import com.frogs.ucenter.entity.ext.UserAttentionInfoExt;
import com.frogs.ucenter.util.wechat.WechatMessageSend;
import com.frogs.ucenter.v1.request.ContactAddRequest;
import com.frogs.ucenter.v1.request.FollowedUserAttentionInfoRequest;
import com.frogs.ucenter.v1.request.FollowedUserAttentionVerifyRequest;
import com.frogs.ucenter.v1.request.UserAttentionAddRequest;
import com.frogs.ucenter.v1.request.UserAttentionDeleteRequest;
import com.frogs.ucenter.v1.request.UserAttentionInfoRequest;
import com.frogs.ucenter.v1.request.UserAttentionListRequest;
import com.frogs.ucenter.v1.request.UserAttentionUpdateRequest;
import com.frogs.ucenter.v1.request.UserAttentionWeightUpdateRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.AttentionInfoResponse;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.DeleteResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.service.UserAttentionService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userAttentionService")
public class UserAttentionServiceImpl extends UserBaseServiceImpl implements UserAttentionService {
	
	private static final Logger log = LoggerFactory.getLogger(UserAttentionServiceImpl.class);
	
	@Resource
	private UserAttentionInfoDao userAttentionDao;
	@Resource
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	@Resource
	private RequestApiHelper requestApiHelper;
	@Resource
	private WechatMessageSend wechatMessageSend;
	
	@Resource
	private FamilyBaseInfoDao familyBaseInfoDao;
	
	@Override
	public Response getList(Request request)  throws Exception {
		PageListResponse<UserAttentionInfoExt> response = new PageListResponse<UserAttentionInfoExt>();
    	
    	try {
    		UserAttentionListRequest listRequest = (UserAttentionListRequest)request;
    		Integer type = listRequest.getType();
    		PageList<UserAttentionInfoExt> list = null;
    		HashMap<String,Object> params = new HashMap<String,Object>();
    		if(listRequest.getFollowedUserId() > 0) { //关注我的人的列表
    			params.put("eqFollowedUserId", listRequest.getFollowedUserId());
    			if (type == HdcAttentionListTypeEnum.ATTENTION_FOLLOWED_LIST.getId()) {
    				params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
    				params.put("orderByClause"," create_time DESC" );
    			} else if (type == HdcAttentionListTypeEnum.ATTENTION_FOLLOWED_AND_REQUEST_LIST.getId()) {
    				params.put("inStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId() + "," + AttentionStateEnum.ATTENTION_STATUS_REQUEST.getId());
    				params.put("orderByClause", "status desc, create_time desc");
    			} else {
    				throw new ServiceOperationException("参数有误");
    			}
    			params.put("eqOpenPlatformId", listRequest.getOpenPlatformId());
    			list = userAttentionDao.selectByMapForFans(params, listRequest.getPageNum(), listRequest.getPageSize());
    		} else if(listRequest.getFollowUserId() > 0) { //我关注的人的列表
    			params.put("eqFollowUserId", listRequest.getFollowUserId());
    			if (type == HdcAttentionListTypeEnum.ATTENTION_FOLLOW_LIST.getId()) {
    				params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
    				params.put("orderByClause", " weight desc , create_time desc");
    			} else if (type == HdcAttentionListTypeEnum.ATTENTION_FOLLOW_AND_RECOMMEND_LIST.getId()) {
    				params.put("inStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId() + "," + AttentionStateEnum.ATTENTION_STATUS_WAIT.getId() + ","
    						+ AttentionStateEnum.ATTENTION_STATUS_REFUSED.getId() + "," + AttentionStateEnum.ATTENTION_STATUS_REQUEST.getId());
    				params.put("orderByClause", "status desc, create_time desc");
    			} else if (type == HdcAttentionListTypeEnum.ATTENTION_FOLLOW_AND_CONTACT_LIST.getId()) {
    				params.put("inStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId() + "," + AttentionStateEnum.ATTENTION_STATUS_NO.getId());
    				params.put("orderByClause", "status asc, weight desc, create_time desc");
    			} else {
    				throw new ServiceOperationException("参数有误");
    			}
    			params.put("eqOpenPlatformId", listRequest.getOpenPlatformId());
    			list = userAttentionDao.selectByMapForAttention(params, listRequest.getPageNum(), listRequest.getPageSize());
    		} else {
    			throw new ServiceOperationException("参数有误");
    		}
    		response.setPageTurn(list.getPageTurn());
    		response.setList(list);
	    	response.setTip("查询关注成功");
	    } catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	/**
	 * 获取等待关注数或等待同意数
	 */
	@Override
	public Response getCount(Request request)  throws Exception {
		ShowResponse<JSONObject> response = new ShowResponse<JSONObject>();
		try{
			UserAttentionListRequest listRequest = (UserAttentionListRequest)request;
    		HashMap<String,Object> params = new HashMap<String,Object>();
    		if(listRequest.getFollowedUserId() > 0) {//关注我的人的列表
    			params.put("eqFollowedUserId", listRequest.getFollowedUserId());
    			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_REQUEST.getId());
    		} else if(listRequest.getFollowUserId() > 0) {//我关注的人的列表
    			params.put("eqFollowUserId", listRequest.getFollowUserId());
    			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_WAIT.getId());
    		}
    		params.put("eqOpenPlatformId", listRequest.getOpenPlatformId());
    		int count = userAttentionDao.selectCountByMap(params);
    		JSONObject result = new JSONObject();
    		result.put("count", count);
    		response.setInfo(result);
	    	response.setTip("查询成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	/**
	 * 取消关注
	 */
	@Override
	public Response delete(Request request) throws Exception  {
		DeleteResponse<UserAttentionInfo> response = new DeleteResponse<UserAttentionInfo>();
    	
    	try {
    		UserAttentionDeleteRequest deleteRequest = (UserAttentionDeleteRequest)request;
    		String ids = deleteRequest.getIds();
    		Map<String,Object> params = new HashMap<String,Object>();
    		if (deleteRequest.getFollowedUserId() > 0) {
    			params.put("eqFollowedUserId", deleteRequest.getFollowedUserId());
    		}
    		if (!StringUtil.isEmpty(ids)) {
    			params.put("inIds", ids);
    		}
    		params.put("eqFollowUserId", deleteRequest.getFollowUserId());
    		params.put("eqOpenPlatformId", deleteRequest.getOpenPlatformId());
    		int count = userAttentionDao.deleteByMap(params);
    		if (count == 0) {
    			throw new RequestIllegalException("删除失败");
    		} else {
    			requestApiHelper.initAlertReceive(deleteRequest.getFollowUserId(), deleteRequest.getFollowedUserId(), HdcReceiveStateEnum.NO_RECEIVE_MESSAGE.getId(), deleteRequest.getOpenPlatformId());
    		}
	    	response.setTip("取消关注成功");
	    } catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	/**
	 * 默认直接同意关注
	 */
	@Override
	public Response insert(Request request) throws Exception  {
		AddResponse<UserAttentionInfo> response = new AddResponse<UserAttentionInfo>();
    	
    	try {
    		UserAttentionAddRequest addRequest = (UserAttentionAddRequest)request;
    		UserAttentionInfo info = new UserAttentionInfo();
    		Integer id = addRequest.getId();
    		Integer followUserId = addRequest.getFollowUserId();
    		Integer followedUserId = addRequest.getFollowedUserId();
    		Integer openPlatformId = addRequest.getOpenPlatformId();
    		UserAttentionInfo contactInfo = null;
    		if (id > 0) { //如果是先填了联系人信息发过来
    			 contactInfo = this.getContactInfo(id, followUserId);
    		}
    		Map<String,Object> params = new HashMap<String,Object>();
    		params.put("eqFollowedUserId", followedUserId);
    		params.put("eqFollowUserId", followUserId);
    		params.put("eqOpenPlatformId", openPlatformId);
    		PageList<UserAttentionInfo> list = userAttentionDao.selectByMap(params, 1, 1, false);
    		if(list.size() == 1){   //如果user_attention_info表中有数据，则更新
    			info = list.get(0);
    			this.updateAttentionInfo(info, addRequest, contactInfo);
    		} else{  //如果user_attention_info表中没有数据，则新增
    			this.insertAttentionInfo(info, addRequest, contactInfo);
    		}
    		if (addRequest.getStatus() == AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
    			this.backwardAttention(followedUserId, followUserId, openPlatformId);
    			this.sendAgreeMsg(followUserId, followedUserId, openPlatformId);
    		}
    		response.setInfo(info);
	    	response.setTip("关注成功");
	    } catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}

	private void sendAgreeMsg(Integer followUserId, Integer followedUserId, Integer openPlatformId) {
		String msg = "nickName已同意您关注sex的健康，请点击查看";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?&redirect_uri=http%3A%2F%2Fw.frogshealth.com%2Fuser%2Fattention%2Findex.html%3Ftype%3D1&appid=wxb30222354415be84&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		this.sendMsg(followUserId, followedUserId, openPlatformId, msg, url);
	}
	
	private void sendMsg(Integer followUserId, Integer followedUserId, Integer openPlatformId, String msg, String url) {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", followUserId);
			params.put("eqOpenPlatformId", openPlatformId);
			PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(params, 1, 1);
			if (list.size() > 0) {
				WechatUserBaseInfo userBaseInfo = list.get(0);
				//String openId = userBaseInfo.getOpenId(); //关注人openId
				params.put("eqUserId", followedUserId);
				list = wechatUserBaseInfoDao.selectByMap(params, 1, 1);
				if (list.size() > 0) {
					userBaseInfo = list.get(0);
					//TODO 未关注的用户获取不了昵称和性别，暂定不发消息
					if (userBaseInfo.getSubScribe() == SwitchEnum.YES.getId()) {
						String nickName = userBaseInfo.getNickName();
						Integer sex = userBaseInfo.getSex();
						String remark = msg.replace("nickName", nickName).replace("sex", (sex == SexEnum.FEMALE.getId() ? "她":"他"));
						String keyword = "请求关注通知";
						String massageStr = TemplateUtil.convert(url, keyword, remark);
						wechatMessageSend.send(followUserId, followedUserId, massageStr, openPlatformId);
					}
				}
			}
		} catch (Exception e) {
			log.error("func[{}] followUserId[{}] followedUserId[{}] msg[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
					followUserId, followedUserId, msg, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
	}
	
	private void updateAttentionInfo(UserAttentionInfo info, UserAttentionAddRequest addRequest,
			UserAttentionInfo contactInfo) throws Exception {
		info.setIsReceiveAlert(addRequest.getIsReceiveAlert());
		//由于状态两种，同意和请求中
		if (addRequest.getStatus() == AttentionStateEnum.ATTENTION_STATUS_WAIT.getId()) {
			if (info.getStatus() != AttentionStateEnum.DELETED.getId()) {
				throw new ServiceOperationException("该数据不能设置待关注状态");
			}
		}
		info.setStatus(addRequest.getStatus());
		info.setCreateTime(new Date());
		if (contactInfo != null) {
			info.setAge(contactInfo.getAge());
			info.setRelatives(contactInfo.getRelatives());
			info.setSex(contactInfo.getSex());
			info.setPhone(contactInfo.getPhone());
			info.setRealName(contactInfo.getRealName());
			userAttentionDao.deleteById(addRequest.getId()); // 清除旧联系人数据
		} else {
			if (!StringUtil.isEmpty(addRequest.getRelatives())) {
    			info.setRelatives(addRequest.getRelatives());
    		} else {
    			info.setRelatives("");
    		}
		}
		if(addRequest.getStatus() == AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
			requestApiHelper.initAlertReceive(addRequest.getFollowUserId(), addRequest.getFollowedUserId(), HdcReceiveStateEnum.RECEIVE_MESSAGE.getId(), addRequest.getOpenPlatformId());
		}
		userAttentionDao.update(info);
	}
	
	private void insertAttentionInfo(UserAttentionInfo info, UserAttentionAddRequest addRequest,
			UserAttentionInfo contactInfo) throws Exception {
		info.setFollowedUserId(addRequest.getFollowedUserId());
		info.setFollowUserId(addRequest.getFollowUserId());
		info.setIsReceiveAlert(addRequest.getIsReceiveAlert());
		info.setStatus(addRequest.getStatus());
		info.setOpenPlatformId(addRequest.getOpenPlatformId());
		FamilyBaseInfo familyBaseInfo = getFamilyBaseInfo(addRequest.getFollowUserId());
		if(familyBaseInfo == null) {
			info.setFamilyId(0);
		} else {
			info.setFamilyId(familyBaseInfo.getId());
		}
		if (contactInfo != null) {
			info.setAge(contactInfo.getAge());
			info.setRelatives(contactInfo.getRelatives());
			info.setSex(contactInfo.getSex());
			info.setPhone(contactInfo.getPhone());
			info.setRealName(contactInfo.getRealName());
			userAttentionDao.deleteById(addRequest.getId()); // 清除旧联系人数据
		} else {
			if (!StringUtil.isEmpty(addRequest.getRelatives())) {
    			info.setRelatives(addRequest.getRelatives());
    		} else {
    			info.setRelatives("");
    		}
		}
		userAttentionDao.insert(info);
		if(addRequest.getStatus() == AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
			requestApiHelper.initAlertReceive(addRequest.getFollowUserId(), addRequest.getFollowedUserId(), HdcReceiveStateEnum.RECEIVE_MESSAGE.getId(), addRequest.getOpenPlatformId());
		}
		
	}
	
	/**
	 * 反相关注
	 * 
	 * @param followUserId
	 * @param followedUserId
	 * @param openPlatformId
	 */
	private void backwardAttention(Integer followUserId, Integer followedUserId, Integer openPlatformId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqFollowUserId", followUserId);
		params.put("eqFollowedUserId", followedUserId);
		params.put("eqOpenPlatformId", openPlatformId);
		PageList<UserAttentionInfo> list = userAttentionDao.selectByMap(params, 1, 1,false);
		if (list.size() > 0) {
			UserAttentionInfo userAttentionInfo = list.get(0);
			if (userAttentionInfo.getStatus() != AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
				userAttentionInfo.setStatus(AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
				userAttentionDao.update(userAttentionInfo);
			}
		} else {
			UserAttentionInfo userAttentionInfo = new UserAttentionInfo();
			userAttentionInfo.setFollowUserId(followUserId);
			userAttentionInfo.setFollowedUserId(followedUserId);
			userAttentionInfo.setOpenPlatformId(openPlatformId);
			userAttentionInfo.setStatus(AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
			
			FamilyBaseInfo familyBaseInfo = getFamilyBaseInfo(followUserId);
			if(familyBaseInfo == null)
				userAttentionInfo.setFamilyId(0);
			else
				userAttentionInfo.setFamilyId(familyBaseInfo.getId());
			
			userAttentionDao.insert(userAttentionInfo);
		}
		
		requestApiHelper.initAlertReceive(followUserId, followedUserId, HdcReceiveStateEnum.RECEIVE_MESSAGE.getId(), openPlatformId);
	}
	
	private FamilyBaseInfo getFamilyBaseInfo(Integer userId){
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("eqUserId", userId);
		
		PageList<FamilyBaseInfo> list = familyBaseInfoDao.selectByMap(params, 1, 1, false);
		if(list.size() == 1)
			return list.get(0);
		else
			return null;
	}
	
	private UserAttentionInfo getContactInfo(Integer id, Integer followUserId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqId", id);
		params.put("eqFollowUserId", followUserId);
		PageList<UserAttentionInfo> list = userAttentionDao.selectByMap(params, 1, 1,false);
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}
	
	@Override
	public Response getAttentionInfo(Request request) throws Exception  {
		AttentionInfoResponse response = new AttentionInfoResponse();
		try {
			UserAttentionInfoRequest infoRequest = (UserAttentionInfoRequest) request;
			Map<String, Object> params = new HashMap<String, Object>();
			if (infoRequest.getId() > 0) {
				params.put("eqId", infoRequest.getId());
			} 
			if (infoRequest.getFollowUserId() > 0) {
				params.put("eqFollowUserId", infoRequest.getFollowUserId());	
			}
			if (infoRequest.getFollowedUserId() > 0) {
				params.put("eqFollowedUserId", infoRequest.getFollowedUserId());
			}
			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
			params.put("eqOpenPlatformId", infoRequest.getOpenPlatformId());
			PageList<UserAttentionInfoExt> infoExts = userAttentionDao.selectByMapForAttention(params, 1, 1);
			if (infoExts.size() == 0) {
				throw new ServiceOperationException("该被关注人不存在");
			}
			response.setUserAttentionInfo(infoExts.get(0));
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	@Override
	public Response getFollowAttentionInfo(Request request) throws Exception  {
		ShowResponse<UserAttentionInfo> response = new ShowResponse<UserAttentionInfo>();
		try {
			FollowedUserAttentionInfoRequest infoRequest = (FollowedUserAttentionInfoRequest) request;
			Integer id = infoRequest.getId();
			Integer followUserId = infoRequest.getFollowUserId();
			UserAttentionInfo userAttentionInfo = userAttentionDao.selectById(id);
			if (!userAttentionInfo.getFollowUserId().equals(followUserId)) {
				throw new ServiceOperationException("数据有误");
			}
			if (userAttentionInfo.getFollowedUserId() > 0) {
				throw new ServiceOperationException("id有误");
			}
			response.setInfo(userAttentionInfo);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	@Override
	public Response update(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserAttentionUpdateRequest updateRequest = (UserAttentionUpdateRequest) request;
			Integer status = updateRequest.getStatus();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqFollowUserId", updateRequest.getFollowUserId());
			params.put("eqFollowedUserId", updateRequest.getFollowedUserId());
			params.put("eqOpenPlatformId", updateRequest.getOpenPlatformId());
			PageList<UserAttentionInfo> list = userAttentionDao.selectByMap(params, false);
			if (list.size() > 0) {
				UserAttentionInfo userAttentionInfo = list.get(0);
				//更新状态有几种
				//1.请求
				if (status == AttentionStateEnum.ATTENTION_STATUS_REQUEST.getId()) {
					if (userAttentionInfo.getStatus() == AttentionStateEnum.ATTENTION_STATUS_WAIT.getId()) {
						userAttentionInfo.setStatus(status);
						this.sendRequestMsg(updateRequest.getFollowedUserId(), updateRequest.getFollowUserId(), updateRequest.getOpenPlatformId());
					} else {
						throw new ServiceOperationException("不合理操作");
					}
				}
				//2.同意
				if (status == AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
					if (userAttentionInfo.getStatus() == AttentionStateEnum.ATTENTION_STATUS_REQUEST.getId()) {
						userAttentionInfo.setStatus(status);
			    		this.backwardAttention(updateRequest.getFollowedUserId(), updateRequest.getFollowUserId(), updateRequest.getOpenPlatformId());
			    		this.sendAgreeMsg(updateRequest.getFollowUserId(), updateRequest.getFollowedUserId(), updateRequest.getOpenPlatformId());
					} else if (userAttentionInfo.getStatus() != AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()){
						throw new ServiceOperationException("不合理操作");
					}
				//3.拒绝
				} else if (status == AttentionStateEnum.ATTENTION_STATUS_REFUSED.getId()) {
					if (userAttentionInfo.getStatus() == AttentionStateEnum.ATTENTION_STATUS_REQUEST.getId()) {
						userAttentionInfo.setStatus(status);
						this.sendRefuseMsg(updateRequest.getFollowUserId(), updateRequest.getFollowedUserId(), updateRequest.getOpenPlatformId());
					} else {
						throw new ServiceOperationException("不合理操作");
					}
				}
				
				if(!StringUtil.isEmpty(updateRequest.getRelatives())) {
					userAttentionInfo.setRelatives(updateRequest.getRelatives());
				}
				if (updateRequest.getAge() > 0) {
					userAttentionInfo.setAge(updateRequest.getAge());
				}
				userAttentionInfo.setSex(updateRequest.getSex());
				if (!StringUtil.isEmpty(updateRequest.getIdentityCard())) {
					userAttentionInfo.setIdentityCard(updateRequest.getIdentityCard());
				}
				if (!StringUtil.isEmpty(updateRequest.getBirthday())) {
					userAttentionInfo.setBirthday(updateRequest.getBirthday());
				}
				if (!StringUtil.isEmpty(updateRequest.getRealName())) {
					userAttentionInfo.setRealName(updateRequest.getRealName());
				}
				if (!StringUtil.isEmpty(updateRequest.getPhone())) {
					userAttentionInfo.setPhone(updateRequest.getPhone());
				}
				userAttentionInfo.setCreateTime(new Date());
				userAttentionDao.update(userAttentionInfo);
			} else {
				throw new ServiceOperationException("不存在");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	private void sendRequestMsg(Integer followUserId, Integer followedUserId, Integer openPlatformId) {
		String msg = "nickName请求关注您的健康，请点击查看";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?&redirect_uri=http%3A%2F%2Fw.frogshealth.com%2Fuser%2Fattention%2Findex.html%3Ftype%3D2&appid=wxb30222354415be84&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		this.sendMsg(followUserId, followedUserId, openPlatformId, msg, url);
	}
	
	private void sendRefuseMsg(Integer followUserId, Integer followedUserId, Integer openPlatformId) {
		String msg = "nickName拒绝您的关注请求(╯﹏╰)";
		String url = "";
		this.sendMsg(followUserId, followedUserId, openPlatformId, msg, url);
	}

	@Override
	public Response verifyAttention(Request request) throws Exception {
		Response response = new DefaultResponse();
		try {
			FollowedUserAttentionVerifyRequest verifyRequest = (FollowedUserAttentionVerifyRequest) request;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqFollowUserId", verifyRequest.getFollowUserId());
			params.put("eqFollowedUserId", verifyRequest.getFollowedUserId());
			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
			params.put("eqOpenPlatformId", verifyRequest.getOpenPlatformId());
			if(verifyRequest.getFollowUserId() == verifyRequest.getFollowedUserId()) {
				throw new ServiceOperationException("您自己不能关注自己");
			}
			PageList<UserAttentionInfoExt> infoExts = userAttentionDao.selectByMapForAttention(params, 1, 1);
			if (infoExts.size() > 0) {
				throw new ServiceOperationException("您已关注过您的小伙伴");
			}
			response.setTip("校验通过");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	@Override
	public Response addContact(Request request) throws Exception {
		ShowResponse<UserAttentionInfo> response = new ShowResponse<UserAttentionInfo>();
		try {
			ContactAddRequest addRequest = (ContactAddRequest) request;
			Integer type = addRequest.getType();
			if (type == 1) {
				UserAttentionInfo attentionInfo = new UserAttentionInfo();
				if (addRequest.getId() > 0) {
					attentionInfo = userAttentionDao.selectById(addRequest.getId());
				}
				attentionInfo.setFollowUserId(addRequest.getUserId());
				attentionInfo.setFollowedUserId(-1);
				attentionInfo.setAge(addRequest.getAge());
				attentionInfo.setPhone(addRequest.getPhone());
				attentionInfo.setRelatives(addRequest.getRelatives());
				attentionInfo.setSex(addRequest.getSex());
				attentionInfo.setOpenPlatformId(addRequest.getOpenPlatformId());
				attentionInfo.setStatus(AttentionStateEnum.ATTENTION_STATUS_NO.getId());
				attentionInfo.setRealName(addRequest.getRealName());
				if (attentionInfo.getId() > 0) {
					userAttentionDao.update(attentionInfo);
				} else {
					userAttentionDao.insert(attentionInfo);
				}
				response.setInfo(attentionInfo);
			} else {
				this.addDefaultContact(addRequest.getUserId(), addRequest.getOpenPlatformId());
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
	private void addDefaultContact(Integer userId, Integer openPlatformId) {
		UserAttentionInfo dad = new UserAttentionInfo();
		dad.setFollowUserId(userId);
		dad.setFollowedUserId(-1);
		dad.setRelatives("爸爸");
		dad.setSex(SexEnum.MALE.getId());
		dad.setOpenPlatformId(openPlatformId);
		dad.setStatus(AttentionStateEnum.ATTENTION_STATUS_NO.getId());
		dad.setCreateTime(DateUtil.getDateAfterMs(new Date(), 4000));
		UserAttentionInfo mom = new UserAttentionInfo();
		mom.setFollowUserId(userId);
		mom.setFollowedUserId(-1);
		mom.setRelatives("妈妈");
		mom.setSex(SexEnum.MALE.getId());
		mom.setOpenPlatformId(openPlatformId);
		mom.setStatus(AttentionStateEnum.ATTENTION_STATUS_NO.getId());
		mom.setCreateTime(DateUtil.getDateAfterMs(new Date(), 3000));
		UserAttentionInfo fatherInLaw = new UserAttentionInfo();
		fatherInLaw.setFollowUserId(userId);
		fatherInLaw.setFollowedUserId(-1);
		fatherInLaw.setRelatives("岳父");
		fatherInLaw.setSex(SexEnum.MALE.getId());
		fatherInLaw.setOpenPlatformId(openPlatformId);
		fatherInLaw.setStatus(AttentionStateEnum.ATTENTION_STATUS_NO.getId());
		fatherInLaw.setCreateTime(DateUtil.getDateAfterMs(new Date(), 2000));
		UserAttentionInfo motherInLaw = new UserAttentionInfo();
		motherInLaw.setFollowUserId(userId);
		motherInLaw.setFollowedUserId(-1);
		motherInLaw.setRelatives("岳母");
		motherInLaw.setSex(SexEnum.MALE.getId());
		motherInLaw.setOpenPlatformId(openPlatformId);
		motherInLaw.setStatus(AttentionStateEnum.ATTENTION_STATUS_NO.getId());
		motherInLaw.setCreateTime(DateUtil.getDateAfterMs(new Date(), 1000));
		List<UserAttentionInfo> list = new ArrayList<UserAttentionInfo>();
		list.add(dad);
		list.add(mom);
		list.add(fatherInLaw);
		list.add(motherInLaw);
		userAttentionDao.batchInsert(list);
	}

	@Override
	public Response updateWeight(Request request) throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserAttentionWeightUpdateRequest updateRequest = (UserAttentionWeightUpdateRequest) request;
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqFollowUserId", updateRequest.getFollowUserId());
			params.put("eqFollowedUserId", updateRequest.getFollowedUserId());
			PageList<UserAttentionInfo> list = userAttentionDao.selectByMap(params, false);
			if (list.size() > 0) {
				UserAttentionInfo userAttentionInfo = list.get(0);
				userAttentionInfo.setWeight(updateRequest.getWeight());
				userAttentionDao.update(userAttentionInfo);
			} else {
				throw new ServiceOperationException("数据不存在");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	    return response;
	}
	
}